#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/1/2 18:36
# @Author  : leon yan
# @Site    : 
# @File    : Globalist.py
# @Software: PyCharm
import json
import queue
import socket
from datetime import date
from enum import Enum

from configobj import ConfigObj

import lib.applets as sApp
from lib.fileprocess import cfgProcess
from lib.qsqledit import QSQL


class QAlarmList(Enum):
    a = "1"
    b = "2"
    c = "3"


global global_config, global_plc_config, global_dict, global_var


# 1 initial
def init():
    globals()["global_config"] = ConfigObj(r".\api\cfg.ini", encoding='UTF8')
    globals()["global_plc_config"] = ConfigObj(r".\api\plc.ini", encoding='UTF8')
    globals()["global_dict"] = {}

    '''obj'''
    set_value("obj_UpdateThread", None)

    '''与PL相关--总体的'''
    set_value('xHasGlobalTrip', 0)
    set_value('xAutoStatus', 0)

    '''其他变量'''
    """
    当前计算机信息显示
    """
    pcName = str(socket.getfqdn(socket.gethostname()))  # get name
    aa = pcName.split('.')
    try:
        pcAddress = socket.gethostbyname(aa[0])  # get ip
    except BaseException as e:
        pcAddress = "127.0.0.1"
        print("err:", e)
    set_value("pcName", pcName)
    set_value("pcAddress", pcAddress)


def systemVariable():
    pass


def deviceInitial():
    """"""
    globals()["global_var"] = cfgProcess.get_cfg_JsonData(r".\api\.variableCfg")

    """设备列表"""
    aFields = ['Num', "Code", 'Name', 'Ip', "Power", "Descriptions"]
    obj = QSQL("Device", "", "order by num", aFields)
    rdData = obj.showLst()
    lst = json.loads(rdData)
    deviceDict = {}
    ipTmpDict = {}
    # print(lst)
    if lst:
        j = 0
        for i in range(len(lst)):
            if lst[i][3]:
                deviceDict[i] = [lst[i][1], lst[i][2], lst[i][3], 0]
            else:
                deviceDict[i] = [lst[i][1], lst[i][2], lst[i][3], 0]

            if lst[i][3]:
                ipTmpDict[j] = [lst[i][3], 0]
                j += 1

    globals()["global_var"]["deviceNum"] = len(lst)
    globals()["global_var"]["deviceDict"] = deviceDict   # 主页的右侧显示["code, name, ip/none, 0/1"]
    globals()["global_var"]["deviceIpDict"] = ipTmpDict      # Ip地址及顺序（顺序从0开始）
    for i in range(len(lst)):
        globals()["global_var"]["bEmergencyStopList"].append(0)
        globals()["global_var"]["bAlarmList"].append(0)
        globals()["global_var"]["bRunningList"].append(0)
    for i in range(len(ipTmpDict)):
        globals()["global_var"]["send_plc_pool"][str(i)] = []

    """生产日志"""
    aFields = ['Id', "LogTime", 'TodayPower', 'TodayAmount', "Operator"]
    obj = QSQL("ProductLog", "", "order by LogTime desc", aFields)
    rdData = obj.showLst()
    lst = json.loads(rdData)
    aa = {}
    aaLen = len(lst)
    for i in range(5):
        if i < aaLen:
            aa[i] = [lst[i][1], lst[i][2], lst[i][3]]
        else:
            aa[i] = ["", 0, 0]
    aa1 = []
    aa2 = []
    for k, v in aa.items():
        aa1.append(v[1])
        aa2.append(v[2])
    global_var["chartMonitor"]["dayAmount"] = aa1
    global_var["chartMonitor"]["dayPower"] = aa2


def initialPlc():
    """"""
    pass


# 2 Plc通信变量
def initial_cfg():
    # Pc
    aa = global_config['Pc']["socketPort"]
    set_value("socketPort", int(aa))

    # '''QRCode'''
    aa = global_config['QRCode']["version"]
    set_value("qr_version", int(aa))
    aa = global_config['QRCode']["size"]
    set_value("qr_size", int(aa))
    aa = global_config['QRCode']["error"]
    set_value("qr_error", int(aa))

    # '''working'''
    aa = global_config['working']["PowerTime"]
    globals()["global_var"]["monitorVar"]["PowerTime"] = int(aa)
    aa = global_config['working']["WorkTime"]
    globals()["global_var"]["monitorVar"]["WorkTime"] = int(aa)
    aa = global_config['working']["AlarmTime"]
    globals()["global_var"]["monitorVar"]["AlarmTime"] = int(aa)

    # '''other'''
    aa = global_config['other']["watt_hour_meter_ip"]
    if aa:
        aa2 = aa.split(",")
    else:
        aa2 = []
    bb = {}
    if aa2:
        for i in range(len(aa2)):
            aa3 = aa2[i].split("_")
            cc = "0"
            if aa3[1] == "正泰":
                cc = "16415"
            elif aa3[1] == "松下":
                cc = "106"
            bb[i] = [aa3[0], cc, 0.0, aa3[1]]
    globals()["global_var"]["watt_hour_meter_ip"] = bb


def List2ListInt(theStr):
    aa = theStr
    for i in range(len(aa)):
        aa[i] = int(aa[i])
    return aa


# 3 Plc通信变量
def initPlcModBus():
    aa = []
    for i in range(13):
        aa.append(0)
    set_value("bEnablePlcWrite", 0)
    set_value("bPlcWriting", 0)
    for i in range(10):
        set_value("bPlcWriting_" + str(0), 0)  # 多PLC时用这个标志位


def set_value(name, value):
    global_dict[name] = value


def get_value(name, defValue=None):
    try:
        return global_dict[name]
    except KeyError:
        return defValue